from sqlalchemy.orm import Session

from app.models.brand import BrandDo
from app.models.category_brand_rel import CategoryBrandRelDo
from app.schemas.brand import BrandVo, BrandBo


def brand_list(db: Session) -> list[BrandVo]:
    """查询全部品牌"""
    brand_do_list = db.query(BrandDo).filter(BrandDo.show_status == 1).order_by(BrandDo.sort).all()
    return [BrandVo.model_validate(b) for b in brand_do_list]


def get_brand(db: Session, brand_id: int) -> BrandVo:
    """获取品牌详情"""
    brand_db = db.query(BrandDo).filter(BrandDo.id == brand_id).one()
    return BrandVo.model_validate(brand_db)


def brand_save(db: Session, brand: BrandBo) -> int:
    """新增品牌"""
    brand_db = BrandDo(**brand.model_dump())
    db.add(brand_db)
    db.commit()
    db.refresh(brand_db)
    return brand_db.id


def brand_edit(db: Session, brand: BrandBo) -> bool:
    """编辑品牌"""
    brand_db = db.query(BrandDo).filter(BrandDo.id == brand.id).first()
    if not brand_db:
        return False
    for k, v in brand.model_dump().items():
        setattr(brand_db, k, v)
    db.commit()
    return True


def brand_delete(db: Session, brand_id: int) -> bool:
    """删除品牌"""
    brand_db = db.query(BrandDo).filter(BrandDo.id == brand_id).first()
    if not brand_db:
        return False
    db.delete(brand_db)
    db.commit()
    return True


def query_brand_by_category_id(db: Session, category_id: int) -> list[BrandVo]:
    """选择品牌"""
    brands = (db.query(BrandDo)
              .join(CategoryBrandRelDo,BrandDo.id == CategoryBrandRelDo.brand_id)
              .filter(CategoryBrandRelDo.category_id == category_id)
              .filter(BrandDo.show_status == 1)
              .all())
    return [BrandVo.model_validate(b) for b in brands]
